
var request = GXmlHttp.create();
var gmarkers = [];
var kml;
var i = 0;
var htmls = [];
var to_htmls = [];
var from_htmls = [];
var side_bar_html = "";

var baseIcon = new GIcon();
baseIcon.iconSize=new GSize(12,20);
baseIcon.shadowSize=new GSize(22,20);
baseIcon.iconAnchor=new GPoint(6,20);
baseIcon.infoWindowAnchor=new GPoint(5,1);
    
var weticon = new GIcon(baseIcon, "http://labs.google.com/ridefinder/images/mm_20_red.png", null, "http://labs.google.com/ridefinder/images/mm_20_shadow.png");
var dryicon = new GIcon(baseIcon, "http://labs.google.com/ridefinder/images/mm_20_green.png", null, "http://labs.google.com/ridefinder/images/mm_20_shadow.png");
var moisticon= new GIcon(baseIcon, "http://labs.google.com/ridefinder/images/mm_20_yellow.png", null, "http://labs.google.com/ridefinder/images/mm_20_shadow.png");
var unkicon = new GIcon(baseIcon, "http://labs.google.com/ridefinder/images/mm_20_gray.png", null, "http://labs.google.com/ridefinder/images/mm_20_shadow.png");




function LoadMap()
{
  map.clearOverlays()
  map.addControl(new GLargeMapControl());
  map.setCenter(new GLatLng(22.5362, 113.9112), 13);
  map.setMapType(G_HYBRID_MAP);


  // Add the Terrain Map Type
  map.addMapType(G_PHYSICAL_MAP);
  // Create a Hierercical map type control
  var hierarchy = new GHierarchicalMapTypeControl();
  // make Google Satellite Hybrid be the satellite default
  hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, null, true);
  // add that control to the map
  map.addControl(hierarchy);
  map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(5,5)));

  map.addControl(new HtmlControl('<form onsubmit="ShowUpdateForm(); return false"><input type="submit" value="Update a Trail!">'), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(75, 6)));


  map.addControl(new HtmlControl('<form onsubmit="stateview(); return false"><input type="submit" value="Reset Map">'), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(210, 6)));



  kml = new GGeoXml("http://kybiketrails.appspot.com/kml/ky.kml");
  map.addOverlay(kml);


  overview = new GOverviewMapControl(new GSize(150, 150));
  map.addControl(overview, new
  GControlPosition(G_ANCHOR_BOTTOM_RIGHT)); 


  }





function MakeMarkers(trail,lat,lng,regionDIV,status,comments,kmlpath,entrydate,max)
{

  kmlpath = "'" + kmlpath + "'"
  var point = new GLatLng(lat,lng);
  var marker = createMarker(point,trail,status,comments,kmlpath,entrydate,max);
  map.addOverlay(marker);
  document.getElementById(regionDIV).innerHTML = document.getElementById(regionDIV).innerHTML + side_bar_html;


}


	 
// A function to create the marker and set up the event window
function createMarker(point,name,status,comments,kmlpath,entrydate,max) 
{
  // var marker = new GMarker(point);
  var marker;
	var html = "";
	var textcolor='#000000';


if(status == 'Wet')
{
	textcolor = '#CC0000';
	marker = new GMarker(point,weticon);
}

if(status == "Moist")
{
	textcolor = '#CC0000';
	marker = new GMarker(point,moisticon);
}


if(status == 'Dry' || status == "Dusty")
{
	textcolor = '#006600';
	marker = new GMarker(point,dryicon);
}

if(status == 'Unknown')
{
	textcolor = '#000000';
	marker = new GMarker(point,unkicon);
}


        gmarkers[i] = marker;

        // The info window version with the "to here" form open
        to_htmls[i] = name + '<br>' + 'Status: ' + '<FONT COLOR="' + textcolor + '">' + status + '</FONT><br>Entry Date: ' + entrydate + '<br>Comments: ' + comments + '<p><small>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
           '<br>Start address:<form action="http://maps.google.com/maps" method="get" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() + 
                  // "(" + name + ")" + 
           '"/>';
        // The info window version with the "to here" form open
        from_htmls[i] = name + '<br>' + 'Status: ' + '<FONT COLOR="' + textcolor + '">' + status + '</FONT><br>Entry Date: ' + entrydate + '<br>Comments: ' + comments + '<p><small>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
           '<br>End address:<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
           '<input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><br>' +
           '<INPUT value="Get Directions" TYPE="SUBMIT">' +
           '<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
                  // "(" + name + ")" + 
           '"/>';
        // The inactive version of the direction info

  	 html =  name + '<br>' + 'Status: ' + '<FONT COLOR="' + textcolor + '">' + status + '</FONT><br>Entry Date: ' + entrydate + '<br>Comments: ' + comments + '<p><small><br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';



        GEvent.addListener(marker, "click", function() {
	  map.setCenter(marker.getPoint()); 
          marker.openInfoWindowHtml(html,{maxContent:max});
        });



        side_bar_html = '<a href="javascript:readmap('+ point.lat() +',' + point.lng() + ',14,'  +  kmlpath + ',' + i +' )()"><FONT COLOR="' + textcolor + '">' + name + '</a><br></FONT>';

        htmls[i] = html;
        i++;
        return marker;
      }

      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        GEvent.trigger(gmarkers[i], "click");
      }
      
            // functions that open the directions forms
      function tohere(i) {
        gmarkers[i].openInfoWindowHtml(to_htmls[i]);
      }
      function fromhere(i) {
        gmarkers[i].openInfoWindowHtml(from_htmls[i]);
      }


function readmap(x,y,zoom,kmlpath,i) 
{
	//map.clearOverlays()
	kml.hide();
	map.setCenter(new GLatLng(x, y), zoom);
 	myclick(i) 
	
	if (kmlpath != "''")
	{
	var kmlline = new GGeoXml(kmlpath)
      map.addOverlay(kmlline);
	}

	}

function ShowUpdateForm()
{
//var ajaxwin=dhtmlwindow.open('ajaxbox', 'ajax', 'updatefiles/Updatepage.html', 'Update a trail', 'width=440px,height=280px,left=300px,top=100px,resize=0,scrolling=0'); return false
var mysurvey=dhtmlmodal.open('ajaxbox', 'ajax', 'updatefiles/Updatepage.html', 'Update a trail', 'width=440px,height=280px,left=300px,top=100px,resize=0,scrolling=0'); return false

}


function stateview()
{
	//gmarkers.show();
	//kml.show();
      //map.clearOverlays()
    //  map.setCenter(new GLatLng(37.58208, -85.60813), 7);
    //  map.setMapType(G_HYBRID_MAP);
location.reload(true);
    // var kml = new GGeoXml("http://kybiketrails.appspot.com/kml/ky.kml");
    // map.addOverlay(kml);



}



function SendData(Trail,Status,Comments) {

if(Trail == '')
{
	alert("No trail selected");
	return;
}

if(Status== '')
{
	alert("No Status selected");
	return;
}

if(Comments== '')
{
	Comments== ' '
}

var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
var datenow = (curr_month + "-" + curr_date + "-" + curr_year);


Comments = Comments.replace(/"/g,"");
Comments = Comments.replace(/'/g,"");
var doodie = [];
doodie[0] = Trail;
doodie[1] = Status;
doodie[2] = Comments;
doodie[3] = datenow 

Request("Add",doodie);

dhtmlmodal.hide();
}



function Request(function_name, opt_argv) 
{


  // If optional arguments was not provided, create it as empty
  if (!opt_argv)
    opt_argv = new Array();
 
  // Find if the last arg is a callback function; save it
  var callback = null;
  var len = opt_argv.length;
  if (len > 0 && typeof opt_argv[len-1] == 'function') {
    callback = opt_argv[len-1];
    opt_argv.length--;
  }
  var async = (callback != null);
 
  // Encode the arguments in to a URI
  var query = 'action=' + encodeURIComponent(function_name);
  for (var i = 0; i < opt_argv.length; i++) {

    var key = 'arg' + i;
    var val = JSON.stringify(opt_argv[i]);
    query += '&' + key + '=' + encodeURIComponent(val);
	
  }
  query += '&time=' + new Date().getTime(); // IE cache workaround

  // See http://en.wikipedia.org/wiki/XMLHttpRequest to make this cross-browser compatible
  var req = new XMLHttpRequest();

  // Create a 'GET' request w/ an optional callback handler 
  req.open('GET', '/rpc?' + query, async);

 
  if (async) {
    req.onreadystatechange = function() {
      if(req.readyState == 4 && req.status == 200) {
        var response = null;
        try {
         response = JSON.parse(req.responseText);
        } catch (e) {
         response = req.responseText;
        }
        callback(response);
      }
    }
  }
 
  // Make the actual request
  req.send(null);
}


